import pandas as pd
import numpy as np
from scipy.sparse import coo_matrix

# 加载矩阵数据
data = pd.read_csv('final/ratings.csv', delimiter='\s+')
print(data)

# 创建稀疏矩阵
row = data['userId']
col = data['movieId']
values = data['rating']

num_users = data['userId'].nunique()
num_items = data['movieId'].nunique()
rating_matrix=data.pivot_table(values='rating', index='userId', columns='movieId').fillna(0)

# 初始化参数
num_factors = 10
num_iterations = 50
regularization = 0.01
confidence = 40

# 初始化用户和物品因子矩阵
user_factors = np.random.normal(size=(num_users, num_factors))
item_factors = np.random.normal(size=(num_items, num_factors))

# 加权交替最小二乘法迭代
for _ in range(num_iterations):
    # 更新用户因子矩阵
    for u in range(num_users):
        Cu = np.diag(confidence * rating_matrix[u].data + 1e-9)
        XtX = item_factors.T.dot(Cu).dot(item_factors) + regularization * np.eye(num_factors)
        Xty = item_factors.T.dot(Cu).dot(rating_matrix[u].toarray().T)
        user_factors[u] = np.linalg.solve(XtX, Xty).flatten()

    # 更新物品因子矩阵
    for j in range(num_items):
        Ci = np.diag(confidence * rating_matrix[:, j].data + 1e-9)
        YtY = user_factors.T.dot(Ci).dot(user_factors) + regularization * np.eye(num_factors)
        Yty = user_factors.T.dot(Ci).dot(rating_matrix[:, j].tocsc().T.toarray())
        item_factors[j] = np.linalg.solve(YtY, Yty).flatten()

# 预测评分
predicted_ratings = user_factors.dot(item_factors.T)

# 输出预测评分矩阵
print(predicted_ratings)